package dawnland03.model.task.impl;

import dawnland03.model.action.parameter.ActionOutputParam;
import dawnland03.model.task.*;
import dawnland03.model.entity.Entity;
import dawnland03.model.action.impl.ActionFactory;
import dawnland03.model.action.Action;
import dawnland03.service.GeneralFacade;

import java.util.List;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Feb 14, 2010
 * Time: 9:12:37 PM
 */
public class MoveToTask extends GroupTask {
    private Integer destinationMatrixCellId;

    public MoveToTask(Entity entity, Integer destinationMatrixCellId) {
        super("MoveToTask", entity);
        this.destinationMatrixCellId = destinationMatrixCellId;
    }

    @Override
    protected void doNextStep() {
        if (getTaskStatus() == TaskStatus.PREPARED.getBeforeStatus()) { //before prepare
            List<Integer> path = GeneralFacade.getClosestPathAsIds(entity, entity.getPosition().getMatrixCell().getId(), destinationMatrixCellId);
            path.remove(0); //current position
            Integer previousMatrixCellId = entity.getPosition().getMatrixCell().getId();
            for (final Integer adiacentMatrixCellId : path) {
                GroupTask moveToCellTask = new GroupTask("MoveToCellTask", entity);

                Action acquireLockAction = ActionFactory.createAcquireLockAction(entity, adiacentMatrixCellId, 5);
                TaskCondition taskCondition = new MoveToTaskCondition(1);
                BaseTask acquireLockTask = new BaseTask("AcquireLockTask", entity, acquireLockAction);
                acquireLockTask.addTaskConditionAfterTaskStatus(TaskStatus.FINISHED, taskCondition);
                moveToCellTask.addTask(acquireLockTask);

                //release the current cell
                Action releaseLockAction = ActionFactory.createReleaseLockAction(entity, previousMatrixCellId);
                BaseTask releaseLockTask = new BaseTask("ReleaseLockTask", entity, releaseLockAction);
                moveToCellTask.addTask(releaseLockTask);

                Action moveAction = ActionFactory.createMoveAction(entity, adiacentMatrixCellId, (long) 1.0);
                BaseTask moveTask = new BaseTask("MoveTask", entity, moveAction);
                moveToCellTask.addTask(moveTask);

                this.addTask(moveToCellTask);

                previousMatrixCellId = adiacentMatrixCellId;
            }
        }
        super.doNextStep();
    }
}
